package com.lionli.netty.demo.rpc.netty;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

/**
 * 客户端业务处理
 *
 * @author LionLi
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter implements Callable {

    private ChannelHandlerContext context;
    private String result;
    private String param;

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("初始化连接......");
        context = ctx;
    }

    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) {
        System.out.println("读取数据......");
        result = msg.toString();
        //唤醒等待的线程
        notify();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }

    /**
     * 被代理对象调用, 发送数据给服务器
     */
    @Override
    public synchronized Object call() throws Exception {
        System.out.println("call 进入");
        context.writeAndFlush(param);
        //等待 channelRead 方法获取到服务器的结果后，唤醒
        wait();
        System.out.println("call 返回");
        return  result;

    }

    public void setParam(String param) {
        this.param = param;
    }
}
